package com.zsk.shop.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.enums.EnumType;
import com.zsk.shop.common.utils.EntityConvertUtils;
import com.zsk.shop.common.utils.PageWithSqlUtil;
import com.zsk.shop.common.utils.ToolUtil;
import com.zsk.shop.entity.ShopBanner;
import com.zsk.shop.enums.EnumBannerType;
import com.zsk.shop.mapper.ShopBannerMapper;
import com.zsk.shop.model.params.AddBannerParams;
import com.zsk.shop.model.params.EditBannerParams;
import com.zsk.shop.model.params.GopBannerListParams;
import com.zsk.shop.model.results.GopBannerListResult;
import com.zsk.shop.model.results.ShopBannerListResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 */
@Service
public class ShopBannerService extends ServiceImpl<ShopBannerMapper, ShopBanner> {

    private static final Logger logger = LoggerFactory.getLogger(ShopBannerService.class);

    public BaseResponse addBanner(AddBannerParams params) {
        if (ToolUtil.isOneEmpty(params, params.getName(), params.getPicture(), params.getIsLongTime())) {
            return BaseResponse.error("参数缺失");
        }
        if (!params.getIsLongTime()) {
            if (ToolUtil.isOneEmpty(params.getStartTime(), params.getEndTime())) {
                return BaseResponse.error("当前非长期下时间未设置");
            }
        }
        ShopBanner banner = EntityConvertUtils.convertAToB(params, ShopBanner.class);
        //EnumBannerType.LINK_WX_MINI_GOODS.getCode()
        banner.setType(params.getType());
        if (banner.getType().equals(EnumBannerType.LINK_WX_MINI_GOODS.getCode())) {
            Integer goodsOrderType = params.getGoodsOrderType();
            banner.setGoodsOrderType(ToolUtil.isEmpty(goodsOrderType) ? 1 : goodsOrderType);
        }
        banner.setIsShow(true);
        banner.setIsDeleted(false);
        banner.setCreateTime(new Date());
        return BaseResponse.success(this.save(banner));
    }

    public BaseResponse bannerDetail(Long id) {
        LambdaQueryWrapper<ShopBanner> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopBanner::getId, id);
        queryWrapper.eq(ShopBanner::getIsDeleted, false);
        queryWrapper.last("limit 1");
        return BaseResponse.success(this.getOne(queryWrapper));
    }

    public BaseResponse bannerUpdate(EditBannerParams params) {
        if (ToolUtil.isOneEmpty(params, params.getId())) {
            return BaseResponse.error("当前id有误");
        }
        ShopBanner oldEntity = getOldEntity(params);
        if (ToolUtil.isEmpty(oldEntity)) {
            return BaseResponse.error("未找到当前banner,修改失败");
        }
        if (!params.getIsLongTime()) {
            if (ToolUtil.isOneEmpty(params.getStartTime(), params.getEndTime())) {
                return BaseResponse.error("当前非长期下时间未设置");
            }
        }
        ShopBanner newEntity = getEntity(params);
        ToolUtil.copyProperties(newEntity, oldEntity);
        newEntity.setUpdateTime(new Date());
        this.updateById(newEntity);
        return BaseResponse.success("修改成功");
    }

    private ShopBanner getOldEntity(EditBannerParams param) {
        return this.getById(param.getId());
    }

    private ShopBanner getEntity(EditBannerParams param) {
        param = EntityConvertUtils.setNullValue(param);
        ShopBanner entity = EntityConvertUtils.convertAToB(param, ShopBanner.class);
        return entity;
    }

    public BaseResponse<ShopBannerListResult> bannerList() {
        LambdaQueryWrapper<ShopBanner> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopBanner::getIsShow, true);
        queryWrapper.eq(ShopBanner::getIsDeleted, false).and(x -> x.eq(ShopBanner::getIsLongTime, false)
                .and(y -> y.ge(ShopBanner::getEndTime, new Date()).le(ShopBanner::getStartTime, new Date()))
                .or().eq(ShopBanner::getIsLongTime, true));
        queryWrapper.orderByDesc(ShopBanner::getSort, ShopBanner::getUpdateTime);
        List<ShopBannerListResult> results = EntityConvertUtils.convertAListToBList(this.list(queryWrapper), ShopBannerListResult.class);
        return BaseResponse.success(results);
    }

    public BaseResponse<GopBannerListResult> mcpBannerList(GopBannerListParams params) {
        LambdaQueryWrapper<ShopBanner> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopBanner::getIsDeleted, false);
        if (ToolUtil.isNotEmpty(params.getName())) {
            queryWrapper.like(ShopBanner::getName, params.getName());
        }
        if (ToolUtil.isNotEmpty(params.getIsShow())) {
            queryWrapper.eq(ShopBanner::getIsShow, params.getIsShow());
        }
        queryWrapper.orderByDesc(ShopBanner::getSort, ShopBanner::getUpdateTime);
        List<ShopBanner> bannerList = this.list(queryWrapper);
        List<GopBannerListResult> results = PageWithSqlUtil.getList(bannerList, GopBannerListResult.class);
        for (GopBannerListResult result : results) {
            result.setTypeStr(EnumBannerType.getNameByCode(result.getType()));
        }
        return BaseResponse.success("分页banner列表获取成功", results, bannerList.size());
    }

    /**
     * 修改是否显示
     *
     * @param id
     * @param toShow
     * @return
     */
    public BaseResponse changeShowByBannerId(Long id, Boolean toShow) {
        ShopBanner shopBanner = this.getById(id);
        shopBanner.setIsShow(toShow);
        shopBanner.setUpdateTime(new Date());
        return BaseResponse.success(this.saveOrUpdate(shopBanner));
    }

    /**
     * top显示
     *
     * @param id
     * @return
     */
    public BaseResponse setTopByBannerId(Long id) {
        LambdaUpdateWrapper<ShopBanner> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ShopBanner::getId, id);
        updateWrapper.set(ShopBanner::getSort, Integer.MAX_VALUE);
        this.update(updateWrapper);
        //将原来有的排序减去1
        this.sortReduceOne(id);
        return BaseResponse.success("该banner置顶成功");
    }

    private void sortReduceOne(Long id) {
        LambdaUpdateWrapper<ShopBanner> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.setSql("sort = sort - 1");
        updateWrapper.ne(ShopBanner::getId, id);
        updateWrapper.ne(ShopBanner::getSort, 0);
        updateWrapper.eq(ShopBanner::getIsDeleted, false);
        this.update(updateWrapper);
    }

    public BaseResponse deleteBannerById(Long id) {
        LambdaUpdateWrapper<ShopBanner> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ShopBanner::getId, id);
        updateWrapper.set(ShopBanner::getIsDeleted, true);
        updateWrapper.set(ShopBanner::getUpdateTime, new Date());
        return BaseResponse.success(this.update(updateWrapper));
    }

    public BaseResponse<EnumType> getBannerType() {
        return BaseResponse.success(EnumBannerType.getList());
    }

}
